<?php

require './includes/config.inc.php';
class Login
{
	// Allow access by all methods
	public $conn;
	// This is a magic method called automatically when class is used
	public function __construct()
	{
		$this->conn = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME)
			or die('I\'m sorry but the server has failed. Please check back soon!');
	}
	
	public function checkUserLogin($email,$password)
	{
		$sql = 'SELECT id, contactName, email FROM employers WHERE email = ? AND password = ?';
		
		// Check their login attempts
		if(isset($_SESSION['attempts']) && $_SESSION['attempts'] >= 3)
		{
			$message['error'] = true;
			$message['message'] = "Too many failed login attempts, come back later!";
			return json_encode($message);
		}
		else
		{
			if($stmt = $this->conn->prepare($sql))
			{
				$stmt->bind_param('ss',$email,$password);
				$stmt->execute();
				$stmt->bind_result($id,$contactName,$email);
				if($stmt->fetch())
				{
					$_SESSION['logged_in'] = true;
					$_SESSION['email'] = $email;
                    $_SESSION['employerID'] = $id;
					$_SESSION['contactName'] = $contactName;
					// Reset login attempts
					$_SESSION['attempts'] = 0;

					$message['error'] = false;
					$message['message'] = "Welcome $email, you are now logged in!";
					return json_encode($message);
				}
				else
				{
					@$_SESSION['attempts'] = $_SESSION['attempts'] + 1;
					$message['error'] = true;
					$message['message'] = "You have entered an incorrect email/password combination.";
					return json_encode($message);
				}
			}
		}
	}

        public function getCompanyName($id)
        {
            $sql = 'SELECT companyName FROM employers WHERE id = ?';

            if($stmt = $this->conn->prepare($sql))
            {
                    $stmt->bind_param('s',$id);
                    $stmt->execute();
                    $stmt->bind_result($companyName);
                    $stmt->fetch();
                    return $companyName;
            }
        }
		
		//  Update User Information -------------------------------------------------------
		 public function UpdateEmployerInfo($company,$contact,$email,$id)
        {
            $sql =  "UPDATE employers 
						SET companyName = '".$company."'
						   ,contactName = '".$contact."'
						   ,email = '".$email."'
						 WHERE id = ".$id." LIMIT 1";

            if($stmt = $this->conn->prepare($sql))
            {
                    $stmt->bind_param('ssss',$company,$contact,$email,$id);
                    $stmt->execute();
					$stmt->close();
                    $message['error'] = false;
					$message['message'] = "Contact Information has been successfully updated!";
					return json_encode($message);
            }
        }
		

        public function getEmployerInfo($employerID)
        {
            $sql = 'SELECT companyName, contactName, email
                        FROM employers
                        WHERE id= ?';
            if($stmt = $this->conn->prepare($sql))
            {
                    $stmt->bind_param('s',$employerID);
                    $stmt->execute();
                    $stmt->bind_result($companyName, $contactName, $email);
                    $stmt->fetch();
                    $employerArray = array(
                                    'companyName'=>$companyName,
                                    'contactName'=>$contactName,
                                    'email'=>$email);
                    return $employerArray;
            }
        }

	/**
	*	Register the user to the site
	*/
	public function registerUser($companyName,$contactName,$email,$password,$captcha,$userPassword)
	{
		// Do some checks to make sure everything is valid before we insert it into the database
		if($captcha != $_SESSION['answer'])
		{
			$error = true;
			$message['error'] = true;
			$message['message'] = "Invalid captcha, please try again!";
			return json_encode($message);
		}
		if(strlen($password) < 3)
		{
			$error = true;
			$message['error'] = true;
			$message['message'] = "Please use a longer password to ensure security!";
			return json_encode($message);
		}
		if(!$this->validateEmailAddress($email))
		{
			$error = true;
			$message['error'] = true;
			$message['message'] = "You have supplied an invalid email address!";
			return json_encode($message);
		}
		if(!isset($error))
		{
			// Check to see if the email exists::
			$sql = "SELECT email FROM employers WHERE email = '$email' LIMIT 1";
			$stmt = $this->conn->query($sql);
			$count = $stmt->num_rows;
			$stmt->close();

			if($count >= 1)
			{
				$message['error'] = true;
				$message['message'] = "I'm sorry but  the email address: $email already has an account associated with it!";
				return json_encode($message);
			}
			else
			{
				// Ok insert employer into the database::
				$sql = "INSERT INTO employers ( companyName,
                                                                contactName,
                                                                email,
                                                                password,
                                                                forgot) VALUES (?,?,?,?,?)";

				// Generate a secret code incase the user forgets password::
				$secret = md5(mt_rand(111111,999999));

				if($stmt = $this->conn->prepare($sql))
				{
					$stmt->bind_param('sssss',$companyName,$contactName,$email,$password,$secret);
					$stmt->execute();
					$stmt->close();

					require_once 'Email.php';
					$Email = new Email;
					if($mail = $Email->registerSuccess($companyName,$contactName,$email,$userPassword))
					{
						$message['error'] = false;
						$message['message'] = "Welcome $contactName, you have successfully signed up!";
						return json_encode($message);
					}
				}
				else
				{
					$message['error'] = true;
					$message['message'] = "Hmm, a weird error occurred, please try again!";
					return json_encode($message);
				}
			}
		}
	}

	public function forgotPassword($email)
	{
		if(!$this->validateEmailAddress($email))
		{
			$error = true;
			$message['error'] = true;
			$message['message'] = "Please enter a valid email!";
			return json_encode($message);
		}
		
		if(!isset($error))
		{
			$sql = "SELECT email FROM employers WHERE email = '$email' LIMIT 1";
			if($stmt = $this->conn->query($sql))
			{
				$count = $stmt->num_rows;
				if($count >= 1)
				{
					// Continue with the emailing of reset details as the email exists
					$sql = "SELECT email,forgot FROM employers WHERE email = ? LIMIT 1";
					if($stmt = $this->conn->prepare($sql))
					{
						$stmt->bind_param('s',$email);
						$stmt->execute();
						$stmt->bind_result($email,$code);
						$stmt->fetch();
						$stmt->close();
						
						require_once 'Email.php';
						$Email = new Email;
						if($send = $Email->sendForgotPassword($email,$code))
						{
							$message['error'] = false;
							$message['message'] = "Thanks, your password reset instructions have been sent to you!";
							return json_encode($message);
						}
						else
						{
							$message['error'] = true;
							$message['message'] = "Hmm, a weird error occurred, please try again!";
							return json_encode($message);
						}
					}
				}
				else
				{
					// The email doesnt exist
					$message['error'] = true;
					$message['message'] = "I'm sorry but that email address doesn't exist!";
					return json_encode($message);
				}
			}
		}
	}
	
	// Email Verification -----------------------------------------------------------------
	public function validateEmailAddress($email)
	{
		$check = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$";
		if(eregi($check,$email))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	//  User Verified ---------------------------------------------------------------------
	public function verify()
	{
		if(isset($_SESSION['logged_in']))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	//   Is User and Admin ---------------------------------------------------------------
	public function superUser($id)
	{		
		$sql = 'SELECT count( * ) as yes
                        FROM employers
                        WHERE id =? AND isAdmin = 1';
						
		if($stmt = $this->conn->prepare($sql))
        {	
			$stmt->bind_param('s',$id);
			$stmt->execute();
            $stmt->bind_result($yes);
            $stmt->fetch();	
			$isSuper = $yes;	
		}	
		
		if($isSuper == true) 
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	//   User Logout ------------------------------------------------------------------------------
	public function logUserOut()
	{
		if(isset($_SESSION['logged_in']))
		{
			// Will destroy all sessions
			if(session_destroy())
			{
				header("Location: index.php");
				exit();
			}
		}
	}
	

	public function mathCaptcha()
	{
		$sum1 = mt_rand(1,9);
		$sum2 = mt_rand(1,9);
		$sum3 = $sum1 + $sum2;
		$_SESSION['answer'] = $sum3;
		return $sum1 . ' + ' . $sum2 . ' = ';
	}
	
	public function validateResetInfo($email,$code)
	{
		$email = strip_tags($email);
		$code = strip_tags($code);
		$sql = "SELECT email,forgot FROM employers WHERE email = '$email' AND forgot = '$code' LIMIT 1";
		if($stmt = $this->conn->query($sql))
		{
			$count = $stmt->num_rows;
			if($count >= 1)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}
	
	public function forgotChangeUserPassword($email,$newPass,$newPass2)
	{
		if($newPass != $newPass2)
		{
			$error = true;
			$message['error'] = true;
			$message['message'] = "I'm sorry but those passwords don't match!";
			return json_encode($message);
		}
		
		/*if(strlen($newPass < 4))
		{
			$message['error'] = true;
			$message['message'] = "I'm sorry but that password is too short!";
			return json_encode($message);
		}*/
		if(!isset($error))
		{
			$sql = "UPDATE employers SET password = ? WHERE email = '".$email."' LIMIT 1";
			if($stmt = $this->conn->prepare($sql))
			{
				$stmt->bind_param('s',$newPass);
				$stmt->execute();
				$stmt->close();
				
				$message['error'] = false;
				$message['message'] = "Thanks your password has been changed!  Please login to continue.";
				return json_encode($message);
			}
		}
	}

	public function changeUserPassword($email,$currentPass,$newPass,$newPass2)
	{
		if($newPass != $newPass2)
		{
			$error = true;
			$message['error'] = true;
			$message['message'] = "I'm sorry but those passwords don't match!";
			return json_encode($message);
		}
		$checkPassQuery = 'SELECT id FROM employers WHERE email = ? AND password = ?';

		// Check their login attempts

                if($stmt = $this->conn->prepare($checkPassQuery))
                {
                        $stmt->bind_param('ss',$email,$currentPass);
                        $stmt->execute();
                        $stmt->bind_result($id);
						
                        if($stmt->fetch())
                        {
                            if(!isset($error))
                            {
									$stmt->close();
                                    $sql = "UPDATE employers 
											SET password = '".$newPass."' 
											WHERE email = '".$email."' LIMIT 1";
					
                                    if($stmt = $this->conn->prepare($sql))
                                    {
											$stmt->bind_param('ss',$newPass,$email);
                                            $stmt->execute();
                                            $stmt->close();

                                            $message['error'] = false;
                                            $message['message'] = "Thanks your password has been changed!  Please login to continue.";
                                            return json_encode($message);
                                    }
                                    else
                                    {
                                        $message['error'] = true;
                                        $message['message'] = "The server has died. Please retry (password Change).";
                                        return json_encode($message);
                                    }
                            }
                        }
                        else
                        {
                                $message['error'] = true;
                                $message['message'] = "You entered the wrong current password.  Please retry.";
                                return json_encode($message);
                        }
                }
                else
                {
                        $message['error'] = true;
                        $message['message'] = "The server has died.  Please retry.";
                        return json_encode($message);
                }
	}
	

	public function __destruct()
	{
		// Close the connection, return true if successful
		$closeConnection = $this->conn->close();
		if($closeConnection){return true;}
	}
}
?>